<template>
  <div>
    <!-- <dialog-comp v-if="showDialog" :v-show-dialog.sync="showDialog" @dialogClose="dialogClose" ref="dialog"></dialog-comp> -->
    <modify-dialog-comp v-if="showDialogModify" :show-child-dialog.sync="showDialogModify" ref="dialogmodify" @modifyFlush="flushTable"></modify-dialog-comp>
    <add-dialog-comp v-if="showDialogAdd" :show-child-dialog.sync="showDialogAdd" ref="dialogadd" @addFlush="flushTable"></add-dialog-comp>
    <t-form
      ref="form"
      :data="formData"
      :label-width="80"
      colon
      @reset="onReset"
      @submit="onSubmit"
      :style="{ marginBottom: '8px' }"
    >
      <t-row style="margin-top: 20px;">
        <t-col :span="10">
          <t-row :gutter="[16, 24]">
            <t-col :flex="1">
              <t-form-item label="链名称" name="name">
                <t-input
                  v-model="formData.chain_name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入链名称"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="链状态" name="status">
                <t-select
                  v-model="formData.con_state"
                  class="form-item-content"
                  :options="CHAIN_STATUS_OPTIONS"
                  placeholder="请选择链状态"
                  :style="{ minWidth: '134px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="创建人" name="user">
                <t-select
                  v-model="formData.create_user"
                  class="form-item-content"
                  placeholder="请选择标签"
                  @focus="getUserList"
                  :options="userList"
                  :keys="{ label: 'real_name', value: 'username' }"
                  multiple
                  :minCollapsedNum="3"
                  @change="handleChangeCreateUser"
                  id="user"
                  :style="{ minWidth: '134px' }"
                />               
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }">查询</t-button>
          <t-button type="reset" variant="base" theme="default">重置</t-button>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="1.5" class="operation-ad-container">
          <t-button @click="handleCreatChain" theme="primary"> 创建链连接 </t-button>
          <t-button @click="handleDeleteChain" variant="base" theme="default" :disabled="!selectedRowKeys.length" :style="{ marginLeft: '8px'}"> 删除链连接 </t-button>
          <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>
          <!-- <t-button @click="columnControllerVisible = true" class="right-aligned-button">显示列配置弹窗</t-button> -->
        </t-col>
      </t-row>
    </t-form>
    <div class="table-container">
      <div class="operation-container">
        <t-button @click="columnControllerVisible = true">显示列配置弹窗</t-button>
      </div>
      <t-table
        :data="data"
        :columns="columns"
        rowKey="id"
        :verticalAlign="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
        @select-change="rehandleSelectChange"
        :loading="dataLoading"
        :headerAffixedTop="true"
        :headerAffixProps="{ offsetTop, container: getContainer }"
        :displayColumns.sync="displayColumns"
        :columnControllerVisible.sync="columnControllerVisible"
        :columnController="{
        fields: this.controlColum,
        dialogProps: { preventScrollThrough: true },
        hideTriggerButton: true,
        }"
      >
        <template #op="slotProps">
          <a class="t-button-link" @click="handleClickConn(slotProps)">连接</a>
          <a class="t-button-link" @click="handleClickModify(slotProps)">编辑</a>
          <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a>          
        </template>
      </t-table>
      <t-dialog 
      header="链连接详情"
      :visible.sync="chainConn" 
      :onClose="closeConn" 
      :onConfirm="closeConn" 
      width='40%'
      >
      <!-- <t-tooltip v-if="chainConnState">链操作成功</t-tooltip> -->
      <t-form v-if="chainConnState"
      :data="formDataConn"
      ref="form1"
      width="auto"
      :disabled="true"
    >
      <!-- <t-form-item label="链名称" name="chain_name">
        <t-input v-model="formData.chain_name" placeholder="请输入链名称" ></t-input>
      </t-form-item> -->
      <t-form-item v-for="(item, index) in this.fail_node" :key="index" label="节点地址:" :name="item.node_name">
        <!-- <t-form-item v-for="(item, index) in addlist" :key="item.id" label="节点地址" :name="item.name"></t-form-item> -->
        <t-input v-model="item.node_name" placeholder="请输入节点名称" style="margin-right: 5px;"></t-input>
        <t-input v-model="item.node_addr"  placeholder="请输入节点ip:port"></t-input>
        <t-space size="20px" style="margin-left: 10px;">
          <t-popup destroyOnClose trigger="click">
            <t-button variant="outline">查看异常日志</t-button>
            <template #content>
              <div>{{ item.msg }}}</div>
            </template>
          </t-popup>
      </t-space>
        <!-- <t-space size="24px">
          <t-button @click="showLogs" style="margin-left: 20px;padding: auto;">查看异常日志</t-button>
        </t-space> -->
        
      </t-form-item>
      </t-form>
      <p v-else>连接成功</p>
      </t-dialog>
      <!-- <t-dialog
      placement="center"
      header="文本溢出对话框标题"
      :visible="chainConnLog"
      :onConfirm="closeLog"
      :onClose="closeLog"
    >
    <p>这里显示文本内容</p> -->
      <!-- </t-dialog> -->
      <t-dialog
        header="确认删除当前所选链？"
        :body="confirmBody"
        :visible.sync="confirmVisible"
        @confirm="onConfirmDelete"
        :onCancel="onCancel"
        @deleteFlush="flushTable"
      >
      </t-dialog>
    </div>
  </div>
  
</template>
<script lang="jsx">
import Vue from 'vue';
import { prefix } from '@/config/global';
// import Trend from '@/components/trend/index.vue';
import modifyDialogComp from './ModifyDialogComp.vue';
import addDialogComp from './AddDialogComp.vue';
import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon} from 'tdesign-icons-vue';
import { getChainConnList, operateChainConn, getUserList } from '@/api/requestApi';

// import Utils from '../../../utils/util.js';

// import {listChains, getChainsDetail, addChains, modifyChains, delChains} from '@/api/chains/data'

import {
  CHAIN_STATUS,
  CHAIN_STATUS_OPTIONS,
} from '@/constants';
import { message } from 'tdesign-vue';


const INITIAL_FORM_DATA = {
  chain_name: '',
  con_state: '',
  create_user: '',
};

const FORM_RULES = {
  chain_name: [{ required: true, message: '请输入链名称', type: 'error' }],
  auth_type: [{ required: true, message: '请选择认证类型', type: 'error' }],
  crypto_hash: [{ required: true, message: '请选择加密算法', type: 'error' }],
  chain_id: [{ required: true, message: '请输入链id', type: 'error' }],
};

const staticColumn = ['row-select', 'id', 'name', 'op'];
const controlColum = ['node_num', 'host_num', 'node_list', 'auth_type', 'crypto_hash', 'create_user', 'create_time', 'update_user', 'update_time'];
export default {
  name: 'list-table',
  
  components:{
    modifyDialogComp,
    addDialogComp,
  },
  inject: ['reload'],
  data() {
    return {
      CHAIN_STATUS,
      CHAIN_STATUS_OPTIONS,
      prefix,
      userList:[],
      showLogs: '',
      chainConn: false,
      chainConnLog: false,
      formData: {...INITIAL_FORM_DATA},
      formDataConn: {},
      chainConnState: false,
      chainConnId: '',
      FORM_RULES: {...FORM_RULES},
      data: [],
      selectedRowKeys: [],
      dataLoading: false,
      value: 'first',
      fail_node: [],
      columnControllerVisible: false,
      displayColumns: staticColumn.concat(['auth_type', 'crypto_hash', 'node_list', 'con_state', 'host_num', 'node_num', 'create_user']),
      controlColum,
      columns: [
        { colKey: 'row-select', type: 'multiple', width: 64, fixed: 'left' },
        {
          title: 'ID',
          fixed: 'left',
          width: 50,
          align: 'left',
          ellipsis: true,
          colKey: 'id',
        },
        {
          title: '链名称',
          width: 100,
          ellipsis: true,
          colKey: 'name',
        },
        {
          title: '认证类型',
          width: 50,
          ellipsis: true,
          colKey: 'auth_type',
          cell: (h, {row}) => {
            const AuthTypeListMap = {
              0: { value: 0, label: 'PK'},
              1: { value: 1, label: 'CERT'},
              2: { value: 2, label: 'PWK'},
            };
            return (
              <div>{AuthTypeListMap[row.auth_type].label}</div>             
            );
          }, 
        },
        {
          title: '加密类型',
          width: 50,
          ellipsis: true,
          colKey: 'crypto_hash',
          cell: (h, {row}) => {
            const cryptoHashListMap = {
              0: { value: 0, label: 'SM3'},
              1: { value: 1, label: 'SHA256'},
            };
            return (
              <div>{cryptoHashListMap[row.crypto_hash].label}</div>             
            );
          }, 
        },
        {
          title: '节点列表',
          width: 100,
          ellipsis: true,
          colKey: 'node_list',
        },
        {
          title: '主机数',
          width: 50,
          ellipsis: true,
          colKey: 'host_num',
        },
        {
          title: '节点数',
          width: 50,
          ellipsis: true,
          colKey: 'node_num',
        },
        { 
          title: '链状态', 
          colKey: 'con_state',
          align: 'left', 
          width: 60, 
          cell: (h, {row}) => {
            const statusNameListMap = {
              0: { label: '未连接', theme: 'warning', icon: <ErrorCircleFilledIcon /> },
              1: { label: '连接成功', theme: 'success', icon: <CheckCircleFilledIcon /> },
              2: { label: '连接失败', theme: 'danger', icon: <CloseCircleFilledIcon /> },
            };
            return (
              // <p>{row}</p>
              <t-tag shape="round" theme={statusNameListMap[row.con_state].theme} variant="light-outline">
                {statusNameListMap[row.con_state].icon}
                {statusNameListMap[row.con_state].label}
              </t-tag>
            );}
        },
        {
          title: '创建人',
          width: 50,
          ellipsis: true,
          colKey: 'create_user',
        },
        {
          title: '创建时间',
          width: 100,
          ellipsis: true,
          colKey: 'create_time',
        }, 
        {
          title: '更新人',
          width: 50,
          ellipsis: true,
          colKey: 'update_user',
        },
        {
          title: '更新时间',
          width: 100,
          ellipsis: true,
          colKey: 'update_time',
        },      
        {
          align: 'left',
          fixed: 'right',
          width: 100,
          colKey: 'op',
          title: '操作',
        },
      ],
      rowKey: 'index',
      tableLayout: 'auto',
      verticalAlign: 'top',
      showDialogModify: false, // 控制弹窗的现实与隐藏
      showDialogAdd: false, // 控制弹窗的现实与隐藏
      bordered: true,
      hover: true,
      rowClassName: (rowKey) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 20,
        total: 100,
        defaultCurrent: 1,
      },
      confirmVisible: false,
      deleteIdx: -1,
      deleteChainName: '',
    };
  },
  computed: {
    confirmBody() {
      if (this.deleteIdx > -1) {
        // console.log(this.deleteChainName)
        // const { chain_name } = this.deleteChainName;
        // return `${chain_name}的链连接信息将被清空，删除后将无法恢复`;
        return '链连接信息将被清空，删除后将无法恢复';
      }
      return '所选链信息批量删除后将无法恢复';
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },
  },
  mounted() {
    this.dataLoading = true;
    // const reqParam = {}
    // getChainConnList()
    this.$request
      .get(getChainConnList())
      .then((res) => {
        console.log(res.data)
        if (res.data.code === '000') {
          this.$message.success(res.data.msg);
          const list = res.data.data;
          this.data = list;
          console.log('后端数据->', this.data)
          this.pagination = {
            ...this.pagination,
            total: list.length,
          };
        } else {
          this.$message.error(res.data.msg);
        }     
      })
      .catch((e) => {
        this.$message.error('系统异常');
        console.log(e)
        
      })
      .finally(() => {
        this.dataLoading = false;
      });
    // this.getUserList()
    // 跨页面调用方法
    // var that = this;
    // Utils.$on('demo', function ('msg') {
    // that.function name(params) {
      
    // };
    // })

  },
  methods: {
    getContainer() {
      return document.querySelector('.tdesign-starter-layout');
    },
    onReset() {
      this.formData.chain_name = '';
      this.formData.con_state = '';
      this.formData.create_user = '';
    },
    onSubmit() {
      this.dataLoading = true;
      const queryData = JSON.parse(JSON.stringify(this.formData));
      if (queryData.con_state !== undefined){
        queryData.con_state = queryData.con_state.toString();
      } 
      let url = getChainConnList()
      Object.keys(queryData).forEach(key =>{
        if (queryData[key].length > 0){
          // 如果该项的obj不为空（等于0也可以），并且是第一个不为空的参数时，直接进行拼接，不用加&
          if(url==='/api/query/chains_conn_list' && queryData[key] || url==='/api/query/chains_conn_list' && queryData[key]===0){
            url=`${url}?${key}=${queryData[key]}`
          // 如果该项的obj不为空（等于0也可以），但不是第一个不为空的参数时，加&进行拼接
          } else if(url!=='/api/query/chains_conn_list' && queryData[key] || url!=='/api/query/chains_conn_list' && queryData[key]===0){
            url=`${url}&${key}=${queryData[key]}`
          }
        }
      })

      this.$request
        .get(url)
        .then((res) => {
          // console.log(res.data)
          if (res.data.code === '000') {
            this.$message.success(res.data.msg);
            const list = res.data.data;
            console.log('data',res.data.data, 'list',list)
            this.data = list;
            // console.log('后端数据', this.data)
            this.pagination = {
              ...this.pagination,
              total: list.length,
            };
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          this.$message.error('系统异常');
          console.log(e)
        })
        .finally(() => {
          this.dataLoading = false;
        });
 
    },
    rehandlePageChange(curr, pageInfo) {
      console.log('分页变化', curr, pageInfo);
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log('统一Change', changeParams, triggerAndData);
    },
    rehandleSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      console.log(selectedRowKeys);
    },
    handleClickConn(slotProps) {
      const reqParam = {"ids": [], "param": {}, "op_type": ''};
      reqParam.ids.push(slotProps.row.id.toString())
      this.chainConnId = slotProps.row.id.toString()
      reqParam.op_type = 3;
      this.chainConn = true;
      this.$request
        .post(operateChainConn(), reqParam)
      // operateChainConn(reqParam)
        .then((res) => {
          console.log(res)
          if (res.data.code === '000') {
            this.$message.success(res.data.msg)
            this.chainConnState = false;
          } else {
            this.$message.error(res.data.msg)
            this.chainConnState = true;
            this.fail_node = res.data.data.node_data;
          }
        })
        .catch((e) => {
          this.$message.error('系统异常');
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      // this.flushTable();
    },
    addOrUpdateRefresh() {
      console.log("text, row");
    },
    handleClickModify(slotProps) {
      this.showDialogModify = true;
      this.$nextTick(()=>{
      // 调用的是d子组件里面的init方法传递行数据      
        this.$refs.dialogmodify.init(slotProps.row);
      })
    },
    // 关闭弹窗组件
    dialogClose() {
      this.showDialogModify = true
    },
    handleCreatChain() {
      this.showDialogAdd = true
      // console.log('fff--->',this.formData)
    },
    
    handleClickDelete(slotProps) {
      this.deleteIdx = slotProps.row.id;
      this.deleteChainName = slotProps.row.name;
      console.log("打印下单选",this.deleteIdx,slotProps)
      this.confirmVisible = true;
    },
    handleDeleteChain() {
      const selectedIdx = this.selectedRowKeys
      // console.log("打印下多选",selectedIdx)
      this.confirmVisible = true;

    },
    onConfirmDelete() {
      // 真实业务请发起请求
      let ids = [];
      const reqParam = {"ids": [], "param": {}, "op_type": ''};
      this.confirmVisible = false;
      // console.log("打印下单选deleteIdx",this.deleteIdx)
      if (this.deleteIdx > -1){
        ids.push(this.deleteIdx)
        // console.log("打印下单选ids",ids)
      } else {
        ids = Array.from(Object.values(this.selectedRowKeys), x=>x);
        // ids = Object.values(this.selectedRowKeys)
        // console.log("打印下多选ids",ids)
      }
      this.ids = ids.map(String)
      reqParam.op_type = 0;
      reqParam.ids = this.ids;
      // console.log("提交的表单内容", reqParam);
      if (ids.length > 0) {
        this.$request
          .post(operateChainConn(), reqParam)
        // operateChainConn(reqParam)
          .then((res) => {
            if (res.data.code === "000") {
              this.$message.success('链连接删除成功');
            } else {
              this.$message.error(res.data.msg)
            }
          })
          .catch((e) => {
            this.$message.error('系统异常');
            console.log(e);
          })
          .finally(() => {
            this.dataLoading = false;
          });
      }
      this.flushTable();
      this.resetIdx();
    },
    // 获取创建人
    getUserList(){
      // getUserList()
      this.$request
        .get(getUserList())
        .then((res) => {
          if (res.data.code === '000') {
            const list = res.data.data;      
            this.userList = list;
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    handleChangeCreateUser(...args) {
      console.log('change', ...args);
    },
    onCancel() {
      this.resetIdx();
    },
    resetIdx() {
      this.deleteIdx = -1;
    },
    closeConn() {
      this.chainConn = false;
    },
    closeLog() {
      this.chainConnLog = false;
    },
    // sleep
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    async flushTable(){
      await this.sleep(1000)
      this.reload();
    }
    // 处理字典
    // mapData(data) {
    //   const mappedData = { ...data };
    //   const sexMap = { '1': '男', '2': '女' };
    //   const typeMap = { '1': '类型1', '2': '类型2', '3': '类型3' };
    //   mappedData.sex = sexMap[data.sex];
    //   mappedData.type = typeMap[data.type];

    //   return mappedData;
    // }
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

.form-item-content {
  width: 50%;
}

.selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-s);
    color: var(--td-text-color-secondary);
  }
.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.operation-ad-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 20px;
}
.right-aligned-button {
  float: right;
}
</style>
